package com.flowplan.ai.controller;

import com.flowplan.ai.service.*;
import com.flowplan.common.dto.ApiResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

/**
 * AI服务控制器
 * 
 * @author FlowPlan Team
 */
@Slf4j
@RestController
@RequestMapping("/api/ai")
@CrossOrigin(origins = "*")
public class AiController {
    
    @Autowired
    private AiService aiService;
    
    /**
     * 获取AI服务状态
     */
    @GetMapping("/status")
    public ApiResponse<AiServiceStatus> getServiceStatus() {
        try {
            AiServiceStatus status = aiService.getServiceStatus();
            return ApiResponse.success("获取服务状态成功", status);
        } catch (Exception e) {
            log.error("获取AI服务状态异常: {}", e.getMessage(), e);
            return ApiResponse.error(500, "获取服务状态失败: " + e.getMessage());
        }
    }
    
    /**
     * 需求分析
     */
    @PostMapping("/analyze-requirement")
    @PreAuthorize("hasRole('USER')")
    public ApiResponse<AiAnalysisResult> analyzeRequirement(@RequestBody RequirementAnalysisRequest request) {
        try {
            if (request.getRequirementText() == null || request.getRequirementText().trim().isEmpty()) {
                return ApiResponse.error("需求内容不能为空");
            }
            
            AiAnalysisResult result = aiService.analyzeRequirement(request.getRequirementText());
            
            if (result.isSuccess()) {
                return ApiResponse.success("需求分析成功", result);
            } else {
                return ApiResponse.error(400, result.getMessage());
            }
            
        } catch (Exception e) {
            log.error("需求分析异常: {}", e.getMessage(), e);
            return ApiResponse.error("需求分析失败: " + e.getMessage());
        }
    }
    
    /**
     * 生成功能设计文档
     */
    @PostMapping("/generate-function-spec")
    @PreAuthorize("hasRole('USER')")
    public ApiResponse<AiDocumentResult> generateFunctionSpec(@RequestBody DocumentGenerationRequest request) {
        try {
            if (request.getRequirement() == null || request.getRequirement().trim().isEmpty()) {
                return ApiResponse.error("需求内容不能为空");
            }
            
            AiDocumentResult result = aiService.generateFunctionSpec(request.getRequirement());
            
            if (result.isSuccess()) {
                return ApiResponse.success("功能设计文档生成成功", result);
            } else {
                return ApiResponse.error(400, result.getMessage());
            }
            
        } catch (Exception e) {
            log.error("功能设计文档生成异常: {}", e.getMessage(), e);
            return ApiResponse.error("文档生成失败: " + e.getMessage());
        }
    }
    
    /**
     * 生成测试用例
     */
    @PostMapping("/generate-test-cases")
    @PreAuthorize("hasRole('USER')")
    public ApiResponse<AiDocumentResult> generateTestCases(@RequestBody DocumentGenerationRequest request) {
        try {
            if (request.getRequirement() == null || request.getRequirement().trim().isEmpty()) {
                return ApiResponse.error("功能描述不能为空");
            }
            
            AiDocumentResult result = aiService.generateTestCases(request.getRequirement());
            
            if (result.isSuccess()) {
                return ApiResponse.success("测试用例生成成功", result);
            } else {
                return ApiResponse.error(400, result.getMessage());
            }
            
        } catch (Exception e) {
            log.error("测试用例生成异常: {}", e.getMessage(), e);
            return ApiResponse.error("测试用例生成失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取智能建议
     */
    @PostMapping("/smart-suggestions")
    @PreAuthorize("hasRole('USER')")
    public ApiResponse<AiSuggestionResult> getSmartSuggestions(@RequestBody SmartSuggestionRequest request) {
        try {
            if (request.getProjectContext() == null || request.getProjectContext().trim().isEmpty()) {
                return ApiResponse.error("项目上下文不能为空");
            }
            
            AiSuggestionResult result = aiService.getSmartSuggestions(request.getProjectContext());
            
            if (result.isSuccess()) {
                return ApiResponse.success("智能建议生成成功", result);
            } else {
                return ApiResponse.error(400, result.getMessage());
            }
            
        } catch (Exception e) {
            log.error("智能建议生成异常: {}", e.getMessage(), e);
            return ApiResponse.error("智能建议生成失败: " + e.getMessage());
        }
    }
    
    /**
     * 生成待办任务建议
     */
    @PostMapping("/generate-todo-suggestions")
    @PreAuthorize("hasRole('USER')")
    public ApiResponse<AiTaskGenerationResult> generateTodoSuggestions(@RequestBody TaskGenerationRequest request) {
        try {
            if (request.getExcelContent() == null || request.getExcelContent().trim().isEmpty()) {
                return ApiResponse.error("Excel内容不能为空");
            }
            
            AiTaskGenerationResult result = aiService.generateTodoSuggestions(request.getExcelContent());
            
            if (result.isSuccess()) {
                return ApiResponse.success("任务建议生成成功", result);
            } else {
                return ApiResponse.error(400, result.getMessage());
            }
            
        } catch (Exception e) {
            log.error("任务建议生成异常: {}", e.getMessage(), e);
            return ApiResponse.error("任务建议生成失败: " + e.getMessage());
        }
    }
    
    /**
     * 需求分析请求
     */
    public static class RequirementAnalysisRequest {
        private String requirementText;
        
        public String getRequirementText() {
            return requirementText;
        }
        
        public void setRequirementText(String requirementText) {
            this.requirementText = requirementText;
        }
    }
    
    /**
     * 文档生成请求
     */
    public static class DocumentGenerationRequest {
        private String requirement;
        
        public String getRequirement() {
            return requirement;
        }
        
        public void setRequirement(String requirement) {
            this.requirement = requirement;
        }
    }
    
    /**
     * 智能建议请求
     */
    public static class SmartSuggestionRequest {
        private String projectContext;
        
        public String getProjectContext() {
            return projectContext;
        }
        
        public void setProjectContext(String projectContext) {
            this.projectContext = projectContext;
        }
    }
    
    /**
     * 任务生成请求
     */
    public static class TaskGenerationRequest {
        private String excelContent;
        
        public String getExcelContent() {
            return excelContent;
        }
        
        public void setExcelContent(String excelContent) {
            this.excelContent = excelContent;
        }
    }
}